package com.feifan.provider.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.feifan.api.dto.OmsMoneyInfoParam;
import com.feifan.api.dto.OmsOrderDeliveryParam;
import com.feifan.api.dto.OmsOrderQueryParam;
import com.feifan.api.dto.OmsReceiverInfoParam;
import com.feifan.api.model.*;
import com.feifan.api.service.IOmsOrderService;
import com.feifan.common.CommonPage;
import com.feifan.provider.mapper.OmsOrderItemMapper;
import com.feifan.provider.mapper.OmsOrderMapper;
import com.feifan.provider.mapper.OmsOrderOperateHistoryMapper;
import com.feifan.provider.mapper.PmsSkuStockMapper;
import com.feifan.provider.rabbitmq.CancelOrderSender;
import com.github.pagehelper.PageHelper;
import org.apache.zookeeper.data.Id;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: FinalProject
 * @author: Xiaofan
 * @createTime: 2021-08-09 13:09
 * @description: Functions of this class is
 **/
@Service(
        version = "1.0.0",
        interfaceName = "com.feifan.api.service.IOmsOrderService",
        interfaceClass = IOmsOrderService.class
)
public class OmsOrderService implements IOmsOrderService {

    @Autowired
    private OmsOrderMapper dao;

    @Autowired
    private CancelOrderSender cancelOrderSender;

    @Autowired
    private OmsOrderOperateHistoryMapper hdao;

    @Autowired
    private PmsSkuStockMapper pdao;

    @Autowired
    private OmsOrderItemMapper idao;

    @Autowired
    private CacheManager cacheManager;

    public void clearCache(){
        cacheManager.getCache("Order").clear();
    }

    @CacheEvict(cacheNames = "Order",key = "#id",allEntries = true,beforeInvocation = false)
    @Override
    public int delete(Long id) {
        clearCache();
        OmsOrder omsOrder=this.detail(id);
        omsOrder.setDeleteStatus(1);//设置成已经删除
        OmsOrderExample omsOrderExample=new OmsOrderExample();
        omsOrderExample.createCriteria().andDeleteStatusEqualTo(0).andIdEqualTo(id);//先将待付款0号的记录取出来，然后删除
        return dao.updateByExampleSelective(omsOrder,omsOrderExample);
    }

    @Cacheable(cacheNames = "Order",unless = "#result==null",key = "#id")
    @Override
    public OmsOrder detail(Long id) {
        return dao.selectByPrimaryKey(id);
    }

    @CachePut(cacheNames = "Order",unless = "#result==null",key = "#id")
    @Override
    public OmsOrder updateNote(Long id, String note, Integer status) {
        clearCache();
        OmsOrder omsOrder=this.detail(id);//先通过id把其所有字段取出来
        omsOrder.setId(id);
        omsOrder.setNote(note);
        omsOrder.setStatus(status);
        omsOrder.setModifyTime(new Date());
        //然后更新下数据库
        dao.updateByPrimaryKeySelective(omsOrder);

        //然后插入新的订单操作
        OmsOrderOperateHistory history=new OmsOrderOperateHistory();
        history.setCreateTime(new Date());
        history.setOrderId(id);
        history.setOperateMan("后台管理员");
        history.setOrderStatus(status);
        hdao.insert(history);//插入数据库
        return omsOrder;
    }

    @CachePut(cacheNames = "Order",key = "#result.id")
    @Override
    public OmsOrder updateReceiverInfo(OmsReceiverInfoParam receiverInfoParam) {
        clearCache();
        OmsOrder omsOrder=this.detail(receiverInfoParam.getOrderId());
        omsOrder.setId(receiverInfoParam.getOrderId());
        omsOrder.setReceiverName(receiverInfoParam.getReceiverName());
        omsOrder.setReceiverPhone(receiverInfoParam.getReceiverPhone());
        omsOrder.setReceiverPostCode(receiverInfoParam.getReceiverPostCode());
        omsOrder.setReceiverDetailAddress(receiverInfoParam.getReceiverDetailAddress());
        omsOrder.setReceiverCity(receiverInfoParam.getReceiverCity());
        omsOrder.setReceiverProvince(receiverInfoParam.getReceiverProvince());
        omsOrder.setReceiverRegion(receiverInfoParam.getReceiverRegion());
        omsOrder.setModifyTime(new Date());
        dao.updateByPrimaryKeySelective(omsOrder);

        //开始插入历史记录
        OmsOrderOperateHistory history=new OmsOrderOperateHistory();
        history.setCreateTime(new Date());
        history.setOrderId(receiverInfoParam.getOrderId());
        history.setOperateMan("后台管理员");
        history.setOrderStatus(receiverInfoParam.getStatus());
        hdao.insert(history);//插入数据库
        return omsOrder;
    }

    @CachePut(cacheNames = "Order",key = "#result.id")
    @Override
    public OmsOrder updateMoneyInfo(OmsMoneyInfoParam moneyInfoParam) {
        clearCache();
        OmsOrder omsOrder=this.detail(moneyInfoParam.getOrderId());
        omsOrder.setId(moneyInfoParam.getOrderId());
        omsOrder.setModifyTime(new Date());
        omsOrder.setFreightAmount(moneyInfoParam.getFreightAmount());
        omsOrder.setDiscountAmount(moneyInfoParam.getDiscountAmount());
        dao.updateByPrimaryKey(omsOrder);

        //开始插入历史记录
        OmsOrderOperateHistory history=new OmsOrderOperateHistory();
        history.setCreateTime(new Date());
        history.setOrderId(moneyInfoParam.getOrderId());
        history.setOperateMan("后台管理员");
        history.setOrderStatus(moneyInfoParam.getStatus());
        history.setNote("修改费用信息");
        hdao.insert(history);//插入数据库
        return omsOrder;

    }

    @CachePut(cacheNames = "Order",key = "#id")
    @Override
    public OmsOrder close(Long id, String note) {
        clearCache();
        OmsOrder omsOrder=this.detail(id);//将其详细信息取出来
        omsOrder.setStatus(4);//改变状态为关闭状态
        OmsOrderExample example=new OmsOrderExample();
        example.createCriteria().andDeleteStatusEqualTo(0).andIdEqualTo(id);
        dao.updateByExampleSelective(omsOrder,example);

        //开始插入历史记录
        OmsOrderOperateHistory history=new OmsOrderOperateHistory();
        history.setCreateTime(new Date());
        history.setOrderId(id);
        history.setOperateMan("后台管理员");
        history.setOrderStatus(4);
        history.setNote("关闭订单：连接"+note);
        hdao.insert(history);//插入数据库
        return omsOrder;
    }

    @Cacheable(cacheNames = "OrderList", unless = "#result==null",
            key = "T(String).valueOf(#pageNum" + '-' + "#pageSize)" +//要将其变成字符串，将其变成唯一的一些字符串
                    ".concat(#queryParam.orderSn!=null?#queryParam.orderSn:'orderSn')" +
                    ".concat(#queryParam.receiverKeyword!=null?#queryParam.receiverKeyword:'receiverKeyword')" +
                    ".concat(#queryParam.status!=null?#queryParam.status:'status')" +
                    ".concat(#queryParam.orderType!=null?#queryParam.orderType:'orderType')" +
                    ".concat(#queryParam.sourceType!=null?#queryParam.sourceType:'sourceType')" +
                    ".concat(#queryParam.createTime!=null?#queryParam.createTime:'createTime')")
    @Override
    public CommonPage list(OmsOrderQueryParam queryParam, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum,pageSize);//通过字段去取出相应的集合
        return CommonPage.restPage(dao.getOrderList(queryParam));
    }

    @CachePut(cacheNames = "Order",key = "#result.id")
    @Override
    public OmsOrder delivery(OmsOrderDeliveryParam deliveryParam) {
        clearCache();
        OmsOrder omsOrder=this.detail(deliveryParam.getOrderId());//通过主键id取出该条数据
        omsOrder.setDeliverySn(deliveryParam.getDeliverySn());
        omsOrder.setDeliveryCompany(deliveryParam.getDeliveryCompany());
        omsOrder.setDeliveryTime(new Date());
        omsOrder.setStatus(2);//修改状态为已发货状态

        //开始插入历史记录
        OmsOrderOperateHistory history=new OmsOrderOperateHistory();
        history.setCreateTime(new Date());
        history.setOrderId(deliveryParam.getOrderId());
        history.setOperateMan("后台管理员");
        history.setOrderStatus(4);
        history.setNote("完成发货");
        hdao.insert(history);//插入数据库
        return omsOrder;
    }

    @Override
    public void sendDelayMessageCancelOrder(Long orderId, int minute) {
        long delayTime=minute*60*1000;//转换成毫秒级别
        cancelOrderSender.sendMessage(orderId,delayTime);
    }

    @CachePut(cacheNames = "Order",key = "#orderId")
    @Override
    public OmsOrder cancelOrder(Long orderId) {
        clearCache();
        OmsOrder omsOrder=this.detail(orderId);
        if(omsOrder!=null){
            //说明找到了要取消的订单
            omsOrder.setStatus(4);//设置订单状态为关闭
            dao.updateByPrimaryKey(omsOrder);

            //进行库存明细解除锁定
            OmsOrderItemExample example=new OmsOrderItemExample();
            example.createCriteria().andOrderIdEqualTo(orderId);
            List<OmsOrderItem> list=idao.selectByExample(example);
            //对其数据进行整合,形成一个新的里面都是产品编号的集合
            List<Long> plist=list.stream().map(c->c.getProductId()).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(plist)){
                //如果该集合不为空
                //操作库存表
                PmsSkuStock pmsSkuStock=new PmsSkuStock();
                PmsSkuStockExample example1=new PmsSkuStockExample();
                example1.createCriteria().andProductIdIn(plist);//在库存里找到上面集合中的库存号
                pmsSkuStock.setLockStock(0);//然后进行解除锁定
                pdao.updateByExampleSelective(pmsSkuStock,example1);//根据上面修改的那些字段，进行部分修改
            }
        }
        return omsOrder;
    }
}